package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import constants.Configurations;
import constants.Default;
import duppentity.Dupps;
import duppentity.UserDupp;
import jj.play.ns.nl.captcha.gimpy.DropShadowGimpyRenderer;
import play.Play;
import play.cache.Cache;
import play.libs.Images;
import play.mvc.Http;
import org.apache.commons.lang.RandomStringUtils;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;


/**
 * Author: yangzhi@djcars.cn
 * Create: 2014-01-03 15:02
 */
public class CaptchaHelper {


    private static String maxAge = Play.configuration.getProperty("captcha.maxAge", "30mn");
    private static final String cookieName = "CTCSEQ";

    /**
     * 设置序号
     *
     * @param request
     * @param response
     */
    public static String setSeq(Http.Request request, Http.Response response,Integer codeType) {
        Http.Cookie cookie = request.cookies.get(cookieName);
        String seq = null;
        Integer len =0;
        Boolean letters =false;
        if (codeType.equals(Default.codeType.one)){
            len = Default.randomLen.one;
            letters = true;
            if (cookie == null || cookie.value.length() != len || !Utils.isLetterOrNumber(cookie.value)) {
                seq = RandomStringUtils.random(len, letters, true);
            } else {
                seq = cookie.value;
            }
        }else if (codeType.equals(Default.codeType.two)){
            len = Default.randomLen.two;
            seq = RandomStringUtils.random(len, letters, true);
        }
        response.setHeader("P3P", "CP=CAO PSA OUR");
        response.setCookie("CTCSEQ", seq, maxAge);
        return seq;
    }

    /**
     * @param seq
     */
    public static String getCacheKey(String seq) {
        return "/capcha/".concat(seq);
    }

    /**
     * 判断某个请求的验证码是否正确的
     *
     * @param request
     * @param captcha
     */
    public static boolean isCorrect(Http.Request request, String captcha,Integer codeType) {
        if (Utils.isNullOrEmpty(captcha)) {
            return false;
        }
        Http.Cookie cookie = request.cookies.get(cookieName);
        if (cookie == null) {
            return false;
        }

        Integer len =0;
        if (codeType.equals(Default.codeType.one)){
            len = Default.randomLen.one;
        }else if (codeType.equals(Default.codeType.two)){
            len = Default.randomLen.two;
        }
        if (cookie.value.length() != len || !Utils.isLetterOrNumber(cookie.value)) {
            return false;
        }

        String cacheKey = getCacheKey(cookie.value);

        Object text = Cache.get(cacheKey);


        //return text != null && captcha.equalsIgnoreCase((String) text);

        if(text != null && captcha.equalsIgnoreCase((String) text)) {
            //去除缓存记录
            if (text != null) {
                Cache.delete(cacheKey);
            }
            return  true;
        }else{
            return false;
        }
    }

    /**
     * 创建验证码图片
     *
     * @param request
     * @param response
     */
    public static void create(Http.Request request, Http.Response response) {
        response.setContentTypeIfNotSet("image/png");
        String seq = setSeq(request, response,Default.codeType.one);
        ImageUtils.CaptchaNew captcha = ImageUtils.captcha(130, 50);
        captcha.fonts.clear();
        captcha.fonts.add(new Font("Arial", Font.PLAIN, 25));
        captcha.fonts.add(new Font("Arial", Font.PLAIN, 25));
        captcha.gimpy = new DropShadowGimpyRenderer();

        captcha.getText(4);

        byte[] buffer = new byte[32];
        int size = 0;
        try {
            while ((size = captcha.read(buffer, 0, buffer.length)) > 0) {
                response.out.write(buffer, 0, size);
            }
            //记录
            Cache.set(getCacheKey(seq), captcha.text, maxAge);
        } catch (IOException e) {
            //response.se
        }
    }

    static UserDupp userDupp = Dupps.get(UserDupp.class);

    /**
     * 发送短信验证码
     * @param request
     * @param response
     * @param mobile
     */
    public static void createCode(Http.Request request, Http.Response response,String mobile){
        String seq =setSeq(request,response,Default.codeType.two);
        JSONObject code= new JSONObject();
        code.put("code",seq);
        JsonObject  data = userDupp.createSms(mobile,Integer.parseInt(Configurations.templateId),JSONObject.toJSONString(code));
        if (data!=null){
            if (data.get("result").getAsLong()>0){
                //记录
                Cache.set(getCacheKey(seq),seq, maxAge);
            }
        }
    }


}
